package com.kly.sc.api.application.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.dynamodbv2.xspec.S;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Response;
import com.google.common.collect.Maps;
import com.kly.dto.AddOrderReq;
import com.kly.dto.MemberDto;
import com.kly.dto.ProductDto;
import com.kly.dto.TOrderDto;
import com.kly.enums.BenefitsStatus;
import com.kly.enums.OrderStatus;
import com.kly.enums.ProductCategory;
import com.kly.enums.SubscriptionProcessStatus;
import com.kly.req.ReceiveNotifyRequest;
import com.kly.sc.api.application.annos.SignIgnore;
import com.kly.sc.api.application.annos.UserBenefitControl;
import com.kly.sc.api.application.config.UserRightsConfig;
import com.kly.sc.api.application.constant.ApiRedisKeys;
import com.kly.sc.api.application.consts.Constants;
import com.kly.sc.api.application.controller.im.request.ReceiveMessageRequest;
import com.kly.sc.api.application.controller.order.OrderController;
import com.kly.sc.api.application.controller.order.request.CreateOrderReq;
import com.kly.sc.api.application.controller.order.rsp.GenerateOrderResp;
import com.kly.sc.api.application.controller.user.request.DoUserLikeRequest;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.service.utils.RedisService;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.sc.api.infras.exception.ApplicationException;
import com.kly.sc.api.infras.utils.HttpUtil;
import com.kly.sc.api.infras.utils.StringUtils;
import com.kly.service.*;
import com.kly.service.pay.RepayService;
import com.kly.user.constant.RedisKey;
import com.kly.user.enums.AppCodeEnum;
import com.kly.user.enums.RememberTime;
import com.kly.user.service.WlmService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * User: yujianfu (mr.vencnet@gmail.com)
 * Date: 2019-11-25
 * Time: 11:08
 */
@RestController
public class OkController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OkController.class);

    @Autowired
    private RedisClient redisClient;
    @Resource
    private WlmService wlmService;

    @Resource
    UserRightsConfig userRightsConfig;
    @Resource
    ProductService productService;
    @Resource
    MemberService memberService;
    @Resource
    MemberBenefitsService memberBenefitsService;
    @Resource
    UserVasPurchasesService userVasPurchasesService;

    @Resource
    RedisService redisService;


    @SignIgnore
    @RequestMapping("/ok")
    public String ok() {
        return "ok-api";
    }



    @SignIgnore
    @RequestMapping("/01")
    public String test01() {
        Map<String, String> agreement = userRightsConfig.getAgreement();
        System.out.println(agreement);
        Map<String, String> customerService = userRightsConfig.getCustomerService();
        System.out.println(customerService);
        return "ok-api";
    }

    @RequestMapping("/02")
    @UserBenefitControl(benefit = "browse")
    public Response test02(@RequestBody DoUserLikeRequest doUserLikeRequest) {

        return null;
    }

    //    @SignIgnore
    @RequestMapping("/03")
    @UserBenefitControl(benefit = "conversations")
    @SignIgnore
    public Response test03(@RequestBody ReceiveMessageRequest messageRequest) {

        return null;
    }


    @RequestMapping("/04")
    @SignIgnore
    public Response test04(String userCode) {
        redisService.setString(ApiRedisKeys.CUSTOMER_SERVICE_USER.getValue(), userCode, userCode);
        return null;
    }

    @RequestMapping("/00")
    @SignIgnore
    public Response test(String key, boolean flag) {
        if (flag) {
            redisService.del(key);
        } else {
        }
        return null;
    }


    @RequestMapping("/addMember")
    public void test05(@RequestBody ProductDto productDto) {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        productDto = getProductDto(productDto.getProductCode());
        createUserBenefits(productDto, userCode);
    }

    public ProductDto getProductDto(String productCode) {
        String appCode = RequestLocalInfo.getRequestBasicInfo().getAppCode();
        Response<ProductDto> listResponse = productService.queryProductsByProductCode(appCode, productCode);
        if (listResponse.isSuccess() && listResponse.getData() != null) {
            return listResponse.getData();
        }
        throw new ApplicationException("The product not exists, productCode=" + productCode);
    }

    private void createUserBenefits(ProductDto productDto, String userCode) {
        ProductCategory category = ProductCategory.fromType(productDto.getProductCategory());
        switch (category) {
            case MEMBER:
                //模拟订单完成调用赋予会员权益接口
                Response<MemberDto> memberInfo = memberService.saveOrUpdateMember(userCode, productDto);
                //新增会员之后更新缓存会员消息
//                long between = DateUtil.between(new DateTime(), new DateTime(memberInfo.getData().getExpiryDate()), DateUnit.SECOND, false);
//                redisClient.set(ApiRedisKeys.USER_MEMBER.getValue(), JSONUtil.toJsonStr(memberInfo.getData()), between, userCode);
                memberBenefitsService.saveMemberBenefits(memberInfo.getData(), productDto);
                break;
            case FLASH_CHAT:
            case PRIVATE_PHOTO:
            case PRIVATE_VIDEO:
                userVasPurchasesService.saveUserPurchasesBenefits(userCode, productDto);
                break;
        }

    }

    @SignIgnore
    @RequestMapping("/clear/{userCode}/{lookingFor}")
    public String clear(@PathVariable String userCode, @PathVariable String lookingFor) {
        redisClient.del(RedisKey.WLM_PASS, userCode, lookingFor);
        redisClient.del(RedisKey.WLM_DISLIKE, userCode, lookingFor);
        redisClient.del(RedisKey.WLM_LIKE, userCode, lookingFor);
        redisClient.del(RedisKey.WLM_DISLIKE, userCode, lookingFor);

        final Response response = wlmService.removeWlmUser(userCode);
        return "Remove result:" + JSONObject.toJSONString(response);
    }

    @Resource
    TOrderService tOrderService;
    /**
     * 商品类型: 1-消耗类 2-订阅类
     */
    public static final Integer purchaseProductType = 1;
    public static final Integer purchaseProductTypeSubscriptions = 2;

    @SignIgnore
    @RequestMapping("/addOrder/{userCode}/{productCode}")
    public String addOrder(@PathVariable String userCode, @PathVariable String productCode) {
        ProductDto productDto = getProductDto(productCode);

        AddOrderReq addOrderReq = new AddOrderReq();
        addOrderReq.setProductDto(productDto);
        addOrderReq.setUserCode(userCode);
        final TOrderDto order = RpcUtils.getResult(tOrderService.saveOrder(addOrderReq));
        GenerateOrderResp resp = new GenerateOrderResp();
        BeanUtils.copyProperties(order, resp);
        resp.setPurchaseType(productDto.getPurchaseType());

        CreateOrderReq createOrderReq = new CreateOrderReq();
        createOrderReq.setProductCode(order.getProductCode());
        createUserBenefits(getProductDto(createOrderReq.getProductCode()), userCode, order.getOrderNo());

        order.setOrderNo(order.getOrderNo());
        order.setStatus(OrderStatus.PAID.getStatus());
        order.setBenefitsStatus(BenefitsStatus.ISSUED.getStatus());
        RpcUtils.getResult(tOrderService.updateOrder(order));

        JSONObject msgJson = new JSONObject();
        msgJson.put("messageId", "1111");
        final ReceiveNotifyRequest receiveNotifyRequest = ReceiveNotifyRequest.builder().receiveNotifyMsg(msgJson.toJSONString()).messageId(msgJson.getString("messageId")).build();
        repayService.addSubscriptionLog(receiveNotifyRequest);

        repayService.updateSubscriptionStatus(msgJson.getString("messageId"), SubscriptionProcessStatus.INIT, "");


        return JSONObject.toJSONString(order);
    }

    @Resource
    OrderController orderController;
    @Resource
    RepayService repayService;

    @SignIgnore
    @RequestMapping("/subscriptionOrder/{userCode}/{productCode}")
    public String subscriptionOrder(@PathVariable String userCode, @PathVariable String productCode) {

        String purchaseToken = "edmeghompoglaleocchijibh.AO-J1OwqyzzAGrtqZ9AFzNzWH8hPKfBubwLt5CS9l1rcDou5ZaUJ7vVi1VsJCv2J0vDa4_0UjHwiqdDKYSIS1vBnNhQALkVLpQ";
        JSONObject msgJson = new JSONObject();
        msgJson.put("messageId", "1111");

        JSONObject subscriptionNotification = new JSONObject();
        subscriptionNotification.put("notificationType", 2);
        subscriptionNotification.put("purchaseToken", purchaseToken);
        subscriptionNotification.put("subscriptionId", "meboo_subscription_101");

        final TOrderDto orderDto = RpcUtils.getResult(tOrderService.queryLatestOrderByPurchaseToken(purchaseToken, AppCodeEnum.MEBOO.getAppCode()));

        orderController.subscriptionOrder("com.kly.meboo",
                subscriptionNotification, orderDto, purchaseToken, "meboo_subscription_101", msgJson);


        return "ok";
    }

    private void createUserBenefits(ProductDto productDto, String userCode, String orderNo) {
        ProductCategory category = ProductCategory.fromType(productDto.getProductCategory());
        final TOrderDto order = RpcUtils.getResult(tOrderService.queryOrderByOrderNo2(orderNo));
        if (BenefitsStatus.ISSUED.getStatus() == order.getBenefitsStatus()) {
            return;
        }
        switch (category) {
            case MEMBER:
                //模拟订单完成调用赋予会员权益接口
                Response<MemberDto> memberInfo = memberService.saveOrUpdateMember(userCode, productDto);
                memberBenefitsService.saveMemberBenefits(memberInfo.getData(), productDto);
                break;
            case FLASH_CHAT:
            case PRIVATE_PHOTO:
            case PRIVATE_VIDEO:
                userVasPurchasesService.saveUserPurchasesBenefits(userCode, productDto);
                break;
        }

        // 更新发放标志
        order.setBenefitsStatus(BenefitsStatus.ISSUED.getStatus());
        tOrderService.updateOrder(order);
    }

    @SignIgnore
    @RequestMapping("/fetchAfInfo")
    public String fetchAfInfo() {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://hq.appsflyer.com/export/com.kly.meboo/partners_report/v5?from=2023-11-25&to=2023-11-25&api_token=RVdnrbmFm9R2fusE3uUidc")
                .get()
                .addHeader("accept", "text/csv")
                .build();

        okhttp3.Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            return e.getMessage();
        }
        return JSONObject.toJSONString(response);
    }


    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();

        String url = "https://api.chatfree-app.com/ok";
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (okhttp3.Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            System.out.println(response.body().string());
        }
    }






}
